package com.bjgov.scoresys.dao;
// default package

import static org.hibernate.criterion.Example.create;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;

import com.bjgov.scoresys.entity.ScoreTree;
import com.bjgov.scoresys.util.Page;

/**
 * A data access object (DAO) providing persistence and search support for
 * ScoreTree entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see .ScoreTree
 * @author MyEclipse Persistence Tools
 */

public class ScoreTreeDAO extends BaseHibernateDAO {
	private static final Log log = LogFactory
			.getLog(ScoreTreeDAO.class);
	// property constants
	public static final String ID="id";
	public static final String CATE_NAME = "cateName";
	public static final String PID = "pid";
	public static final String DEEP_PATH = "deepPath";
	public static final String IS_CONTROL = "isControl";
	public static final String HAS_SCORE_ITEM = "hasScoreItem";
	public static final String STATUS = "status";
	public static final String PERCENT = "percent";

	public void save(ScoreTree transientInstance) {
		log.debug("saving ScoreTree instance");
		try {
			getSession().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(ScoreTree persistentInstance) {
		log.debug("deleting ScoreTree instance");
		try {
			getSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public ScoreTree findById(java.lang.Integer id) {
		log.debug("getting ScoreTree instance with id: " + id);
		try {
			ScoreTree instance = (ScoreTree) getSession().get("com.bjgov.scoresys.entity.ScoreTree", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	public List<ScoreTree> findByPIDs(int[] pidarr) {
		log.debug("getting ScoreTree instance by pids: " + Arrays.toString(pidarr));
		try {
			String queryString = "from ScoreTree as model where";
			for(int i=0; i<pidarr.length; i++) {
				queryString += " model.deepPath like '" + pidarr[i] + "%'";
				if(i!=pidarr.length-1) queryString += " or ";
			}
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List<ScoreTree> findByExample(ScoreTree instance) {
		
		
		
		
		log.debug("finding ScoreTree instance by example");
		try {
			List<ScoreTree> results = (List<ScoreTree>) getSession()
					.createCriteria("ScoreTree").add(create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding ScoreTree instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from ScoreTree as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List<ScoreTree> findByCateName(Object cateName) {
		return findByProperty(CATE_NAME, cateName);
	}

	public List<ScoreTree> findByPid(Object pid) {
		return findByProperty(PID, pid);
	}

	public List<ScoreTree> findByDeepPath(Object deepPath) {
		return findByProperty(DEEP_PATH, deepPath);
	}

	public List<ScoreTree> findByIsControl(Object isControl) {
		return findByProperty(IS_CONTROL, isControl);
	}

	public List<ScoreTree> findByHasScoreItem(Object hasScoreItem) {
		return findByProperty(HAS_SCORE_ITEM, hasScoreItem);
	}

	public List<ScoreTree> findByStatus(Object status) {
		return findByProperty(STATUS, status);
	}

	public List<ScoreTree> findByPercent(Object percent) {
		return findByProperty(PERCENT, percent);
	}

	public List findAll() {
		log.debug("finding all ScoreTree instances");
		try {
			String queryString = "from ScoreTree";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public ScoreTree merge(ScoreTree detachedInstance) {
		log.debug("merging ScoreTree instance");
		try {
			ScoreTree result = (ScoreTree) getSession().merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(ScoreTree instance) {
		log.debug("attaching dirty ScoreTree instance");
		try {
			getSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(ScoreTree instance) {
		log.debug("attaching clean ScoreTree instance");
		try {
			getSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
	
	public int getMaxID() {
		log.debug("getMaxID ScoreTree instance");
		try {
			//String queryString = "select max(a.id)  from score_tree a";
			//return (Integer)getSession().createQuery(queryString).uniqueResult();
			String sql = "select max(a.id) as maxId  from score_tree a ";
			return  (Integer)(getSession().createSQLQuery(sql).addScalar("maxId", Hibernate.INTEGER) ).uniqueResult();
		} catch (RuntimeException re) {
			log.error("getMaxID failed", re);
			//throw re;
			return 0;
		}
	}

	@Override
	public int count() {
		log.debug("getScoreTreeCount");
		try {
			String queryString = "select count(id) from ScoreTree";
			Query query = getSession().createQuery(queryString);
	        return (Integer) query.iterate().next();
		} catch (RuntimeException re) {
			log.error("getScoreTreeCount failed", re);
			throw re;
		}
	}

	@Override
	public List getByPage(Page page) throws HibernateException {
		String querySentence = "from ScoreTree";
		Query query = getSession().createQuery(querySentence);
		// 实现分页功能
		query.setFirstResult(page.getBeginIndex())
		.setMaxResults(page.getEveryPage());
		return query.list();
	}
	
}